﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;
using Wuqi.Webdiyer;

namespace MxWeiXinPF.Web.admin.order
{
    public partial class sale_order : MxWeiXinPF.Web.UI.ManagePage
    {
        protected string action = MXEnums.ActionEnum.Add.ToString();
        protected MxWeiXinPF.Model.manager admin_info;
        private MxWeiXinPF.BLL.wx_shop_product caBll = new MxWeiXinPF.BLL.wx_shop_product();
        protected int catalogId = 0;
        protected int category_id = 0;
        private int id = 0;
        protected MxWeiXinPF.Model.orders model = null;
        protected int shopid = 0;
        protected int totalCount;
        private int wid = 0;

        private void AspNetPager1_PageChanging(object src, PageChangingEventArgs e)
        {
            this.AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            this.RptBind(this.CombSqlTxt(), "sort_id asc,id desc", e.NewPageIndex, 5);
        }

        protected void bnSelectUser_Click(object sender, EventArgs e)
        {
            base.ChkAdminLevel("sale_order", MXEnums.ActionEnum.View.ToString());
            if (this.tbUserName.Text.Equals(""))
            {
                base.JscriptMsg("用户过多，请输入关键字查询，支持模糊查找！", "", "Error");
            }
            else
            {
                this.gv_DataBindUser();
            }
        }

        protected void btn_OK_Click(object sender, EventArgs e)
        {
            int num = 0;
            string productlistid = "0";
            for (int i = 0; i < this.rptList.Items.Count; i++)
            {
                int num3 = Convert.ToInt32(((HiddenField)this.rptList.Items[i].FindControl("hidId")).Value);
                CheckBox box = (CheckBox)this.rptList.Items[i].FindControl("chkId");
                if (box.Checked)
                {
                    num++;
                    productlistid = productlistid + "," + num3.ToString();
                }
            }
            if (num > 0)
            {
                this.DivProductList.Style["Display"] = "None";
                if (!this.huserid.Value.ToString().Equals(""))
                {
                    this.saveSaleOrder(int.Parse(this.huserid.Value.ToString()), productlistid);
                }
                else
                {
                    base.JscriptMsg("选择商品前，请先选择客户！", "back", "Error");
                }
            }
            else
            {
                base.JscriptMsg("添加商品时，请至少选择一个商品！", "back", "Error");
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.RptBind(this.CombSqlTxt(), "sort_id asc,id desc", 1, 5);
        }

        protected void btnSelectProduct_Click(object sender, EventArgs e)
        {
            this.DivProductList.Style["Display"] = "Block";
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (this.ddlexpress.SelectedValue.Equals(""))
            {
                base.JscriptMsg("请选择发货方式！", "back", "Error");
            }
            else if (this.ddlpayment.SelectedValue.Equals(""))
            {
                base.JscriptMsg("请选择支付方式！", "back", "Error");
            }
            else
            {
                try
                {
                    MxWeiXinPF.BLL.orders orders = new MxWeiXinPF.BLL.orders();
                    Repeater repeater = this.Repeater1;
                    decimal num = 0M;
                    for (int i = 0; i < repeater.Items.Count; i++)
                    {
                        int num4;
                        int id = Convert.ToInt32(((HiddenField)repeater.Items[i].FindControl("hgoodsid")).Value);
                        decimal num5 = Convert.ToDecimal(((HiddenField)repeater.Items[i].FindControl("hreal_price")).Value);
                        if (!int.TryParse(((TextBox)repeater.Items[i].FindControl("txtquantity")).Text.Trim(), out num4))
                        {
                            num4 = 0x63;
                        }
                        orders.UpdateGoodsQty(id, "quantity=" + num4.ToString());
                        num += num5 * num4;
                    }
                    if (this.id == 0)
                    {
                        string strid = this.horderid.Value;
                        if (!string.IsNullOrEmpty(strid))
                        {
                            this.id = Convert.ToInt32(strid);
                        }
                    }
                    this.model = orders.GetModel(this.id);
                    this.model.real_amount = num;
                    this.model.payable_amount = num;
                    if (this.ddlpayment.SelectedValue.Equals("1"))
                    {
                                      
                        this.model.order_amount = this.model.real_amount + this.model.payment_fee;
                    }
                    else
                    {
                        this.model.order_amount = (this.model.real_amount + this.model.express_fee) + this.model.payment_fee;
                    }
                    orders.Update(model);
                    //orders.UpdateField(this.id, "order_amount=" + num);
                    base.AddAdminLog(MXEnums.ActionEnum.Edit.ToString(), "订单创建成功");
                    base.JscriptMsg("订单创建成功！", "back", "Success");
                }
                catch (Exception exception)
                {
                    base.JscriptMsg("订单创建失败！" + exception.Message, "back", "Success");
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            this.DivProductList.Style["Display"] = "None";
        }

        protected string CombSqlTxt()
        {
            StringBuilder builder = new StringBuilder();
            if (!this.tbProductName.Text.Trim().Equals(""))
            {
                builder.Append(" and  (isnull(productname,'')  like '%" + this.tbProductName.Text.Trim() + "%' or  isnull(PYCODE,'')  like '%" + this.tbProductName.Text.Trim() + "%' ) ");
            }
            if (!this.tbfactory.Text.Trim().Equals(""))
            {
                builder.Append(" and  (isnull(factory,'')  like '%" + this.tbfactory.Text.Trim() + "%' ) ");
            }
            if (!this.tbsku.Text.Trim().Equals(""))
            {
                builder.Append(" and isnull(sku,'')  like '%" + this.tbsku.Text.Trim() + "%' ");
            }
            if (!this.tbwareid.Text.Trim().Equals(""))
            {
                builder.Append(" and isnull(wareid,'')  like '%" + this.tbwareid.Text.Trim() + "%' ");
            }
            if (this.admin_info != null)
            {
                builder.Append(" and shopid=" + this.admin_info.id + " ");
            }
            else
            {
                this.admin_info = base.GetAdminInfo();
                builder.Append(" and shopid=" + this.admin_info.id + " ");
            }
            return builder.ToString();
        }

        protected void dgUser_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "SelectName")
            {
                int itemIndex = e.Item.ItemIndex;
                this.tbUserName.Text = this.dgUser.Items[itemIndex].Cells[2].Text;
                this.hopenid.Value = this.dgUser.Items[itemIndex].Cells[1].Text;
                this.huserid.Value = this.dgUser.Items[0].Cells[0].Text;
                this.DivDoctorList.Style["Display"] = "None";
            }
        }

        private void expressBind()
        {
            Model.manager weixin = base.GetAdminInfo();
            MxWeiXinPF.BLL.express express = new MxWeiXinPF.BLL.express();

            DataTable table = express.GetExpressList100(weixin.parentid).Tables[0];
            this.ddlexpress.Items.Clear();
            this.ddlexpress.Items.Add(new ListItem("请选择发货方式...", ""));
            foreach (DataRow row in table.Rows)
            {
                this.ddlexpress.Items.Add(new ListItem(row["title"].ToString(), row["id"].ToString()));
            }
        }

        private void gv_DataBindUser()
        {
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBString"].ConnectionString))
            {
                connection.Open();
                string selectCommandText = "[sp_FindUser_SaleOrder]";
                try
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(selectCommandText, connection)
                    {
                        SelectCommand = { CommandType = CommandType.StoredProcedure }
                    };
                    if (!this.tbUserName.Text.Equals(""))
                    {
                        adapter.SelectCommand.Parameters.Add(new SqlParameter("@nickname", SqlDbType.VarChar, 50));
                        adapter.SelectCommand.Parameters["@nickname"].Value = this.tbUserName.Text.Trim();
                    }
                    if (!(this.wid.Equals("") || (this.wid == 0)))
                    {
                        adapter.SelectCommand.Parameters.Add(new SqlParameter("@wid", SqlDbType.Int));
                        adapter.SelectCommand.Parameters["@wid"].Value = this.wid;
                    }
                    
                    if (this.shopid != 39)
                    {
                        adapter.SelectCommand.Parameters.Add(new SqlParameter("@shopid", SqlDbType.Int));
                        adapter.SelectCommand.Parameters["@shopid"].Value = this.shopid;
                    }
                    
                    DataSet dataSet = new DataSet();
                    adapter.Fill(dataSet, "Table");
                    this.dgUser.DataSource = dataSet;
                    this.dgUser.DataBind();
                    if (this.dgUser.Items.Count >= 1)
                    {
                        this.DivDoctorList.Style["Display"] = "Block";
                    }
                    else
                    {
                        base.JscriptMsg("找不到跟输入内容相关的内容，请重新输入！", "", "Success");
                    }
                }
                catch (SqlException exception)
                {
                    base.JscriptMsg(exception.Errors[0].Message, "", "Error");
                }
                catch (Exception exception2)
                {
                    base.JscriptMsg(exception2.Message, "", "Error");
                }
            }
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            this.DivDoctorList.Style["Display"] = "None";
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            this.DivProductList.Style["Display"] = "None";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string queryString = MXRequest.GetQueryString("action");
            this.AspNetPager1.PageChanging += new PageChangingEventHandler(this.AspNetPager1_PageChanging);
            this.AspNetPager1.PageSize = 10;
            if (this.admin_info != null)
            {
                this.shopid = this.admin_info.id;
            }
            else
            {
                this.admin_info = base.GetAdminInfo();
                this.shopid = this.admin_info.id;
            }
            MxWeiXinPF.Model.manager weiXinCode = base.GetAdminInfo();
            this.wid = weiXinCode.parentid;
            if (!string.IsNullOrEmpty(queryString) && (queryString == MXEnums.ActionEnum.Edit.ToString()))
            {
                this.action = MXEnums.ActionEnum.Edit.ToString();
                this.id = MXRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    base.JscriptMsg("传输参数不正确！", "back", "Error");
                    return;
                }
                this.ShowInfo(this.id);
            }
            if (!this.Page.IsPostBack)
            {
                this.TreeBind();
                this.expressBind();
                this.paymentBind();
                
                if (this.action == MXEnums.ActionEnum.Edit.ToString())
                {
                }
            }
        }

        private void paymentBind()
        {
            Model.manager weixin = base.GetAdminInfo();
            MxWeiXinPF.BLL.payment payment = new MxWeiXinPF.BLL.payment();
            DataTable table = payment.GetList(0, "  is_lock=0 and wid=" + weixin.parentid, "  sort_id asc").Tables[0];
            this.ddlpayment.Items.Clear();
            this.ddlpayment.Items.Add(new ListItem("请选择支付方式...", ""));
            foreach (DataRow row in table.Rows)
            {
                this.ddlpayment.Items.Add(new ListItem(row["title"].ToString(), row["ptypeid"].ToString()));
            }
        }

        private void RptBind(string _strWhere, string _orderby, int pagecount, int PageSize)
        {
            if (!this.ddlCategoryId.SelectedValue.Equals(""))
            {
                this.category_id = int.Parse(this.ddlCategoryId.SelectedValue);
            }
            _strWhere = " upselling=1   " + _strWhere;
            MxWeiXinPF.Model.manager weiXinCode = base.GetAdminInfo();
            int recordCount = 0;
            DataSet set = this.caBll.GetList(weiXinCode.id, this.category_id, PageSize, pagecount, _strWhere, _orderby, out recordCount);
            this.AspNetPager1.RecordCount = recordCount;
            this.rptList.DataSource = set;
            this.rptList.DataBind();
            if (this.rptList.Items.Count >= 1)
            {
                this.DivProductList.Style["Display"] = "Block";
            }
            else
            {
                ScriptManager.RegisterStartupScript((Page)this, base.GetType(), DateTime.Now.ToString(), "layermsg('没有与输入相关的内容，请重新输入查询！',6);", true);
            }
        }

        private void saveSaleOrder(int userid, string productlistid)
        {
            int pTypeId = 0;
            int id = 0;
            MxWeiXinPF.Model.users model = new MxWeiXinPF.BLL.users().GetModel(userid);
            id = int.Parse(this.ddlexpress.SelectedValue);
            if (id == 0)
            {
                base.JscriptMsg("请选择配送方式！", "back", "Error");
                return;
            }
            else
            {
                pTypeId = int.Parse(this.ddlpayment.SelectedValue);
                IList<MxWeiXinPF.Model.wx_shop_user_addr> openidAddrName = new MxWeiXinPF.BLL.wx_shop_user_addr().GetOpenidAddrName(model.wxOpenId, this.wid);
                if (openidAddrName == null || openidAddrName.Count <= 0)
                {
                    //base.JscriptMsg("该用户没有填写地址信息,请重新选择！", "back", "Error");
                   // return;
                }
                IList<MxWeiXinPF.Model.cartProduct> source = new MxWeiXinPF.BLL.wx_shop_cart().GetProductList_SaleOrder(model.wxOpenId, this.wid, productlistid);
                decimal num3 = source.Sum<MxWeiXinPF.Model.cartProduct>((Func<MxWeiXinPF.Model.cartProduct, decimal>)(c => c.totPrice));
                decimal num4 = source.Sum<MxWeiXinPF.Model.cartProduct>((Func<MxWeiXinPF.Model.cartProduct, decimal>)(c => c.RatePrice));
                MxWeiXinPF.Model.express express2 = new MxWeiXinPF.BLL.express().GetModel(id);
                MxWeiXinPF.Model.payment modelBypTypeIdAndWid = new MxWeiXinPF.BLL.payment().GetModelBypTypeIdAndWid(pTypeId, this.wid);
                string tempaddr = (openidAddrName == null || openidAddrName.Count <= 0) ? "" : openidAddrName[0].province;
                tempaddr += "";
                tempaddr = (openidAddrName == null || openidAddrName.Count <= 0) ? "" : openidAddrName[0].city;
                tempaddr += "";
                tempaddr = (openidAddrName == null || openidAddrName.Count <= 0) ? "" : openidAddrName[0].area;
                tempaddr += "";
                tempaddr += (openidAddrName == null || openidAddrName.Count <= 0) ? "" : openidAddrName[0].addrDetail;
                MxWeiXinPF.Model.orders orders = new MxWeiXinPF.Model.orders
                {
                    order_no = "b" + Utils.GetOrderNumber(),
                    wid = this.wid,
                    openid = model.wxOpenId,
                    modelName = "微商城",
                    modelCode = "shop",
                    modelActionName = "",
                    modelActionId = 0,
                    user_id = model.id,
                    parentid = model.parentopenid,
                    shopid = this.shopid,
                    user_name = "",
                    payment_id = pTypeId,
                    express_id = id,
                    accept_name = ( openidAddrName == null || openidAddrName.Count <= 0) ? model.user_name :openidAddrName[0].contractPerson,
                    post_code = "",
                    telphone = (openidAddrName == null || openidAddrName.Count <= 0) ? model.telphone : openidAddrName[0].tel,
                    mobile = (openidAddrName == null || openidAddrName.Count <= 0) ? model.mobile : openidAddrName[0].tel,
                    area = (openidAddrName == null || openidAddrName.Count <= 0) ? model.province : openidAddrName[0].province,
                    city = (openidAddrName == null || openidAddrName.Count <= 0) ? model.city: openidAddrName[0].city,
                    district = (openidAddrName == null || openidAddrName.Count <= 0) ? model.country : openidAddrName[0].area,
                    address = tempaddr,
                    message = "",
                    payable_amount = num3,
                    real_amount = num3,
                    status = 1
                };
                if (pTypeId == 1)
                {
                    orders.payment_status = 0;
                    orders.express_status = 1;
                    orders.express_fee = 0M;
                }
                else
                {
                    orders.payment_status = 1;
                    orders.express_status = 1;
                    orders.express_fee = express2.express_fee;
                }
                bool quicklyFH = false;
                if (pTypeId == 3)
                {
                    if (modelBypTypeIdAndWid.poundage_type == 1)
                    {
                        orders.payment_fee = (orders.real_amount * modelBypTypeIdAndWid.poundage_amount) / 100M;
                    }
                    else
                    {
                        orders.payment_fee = modelBypTypeIdAndWid.poundage_amount;
                    }
                    MxWeiXinPF.BLL.wx_payment_wxpay _wxpay = new MxWeiXinPF.BLL.wx_payment_wxpay();
                    quicklyFH = _wxpay.GetModelByWid(this.wid).quicklyFH;
                }
                if (quicklyFH)
                {
                    orders.express_status = 0;
                }
                if (pTypeId == 3)
                {
                    orders.order_amount = (orders.real_amount + orders.express_fee) + orders.payment_fee;
                }
                else
                {
                    orders.order_amount = orders.real_amount;
                }
                orders.rate_amount = num4;
                orders.point = 0;
                orders.add_time = DateTime.Now;
                List<MxWeiXinPF.Model.order_goods> list3 = new List<MxWeiXinPF.Model.order_goods>();
                foreach (MxWeiXinPF.Model.cartProduct product in source)
                {
                    MxWeiXinPF.Model.order_goods item = new MxWeiXinPF.Model.order_goods
                    {
                        goods_id = product.productId,
                        goods_title = product.productName,
                        market_price = product.markertprice,
                        sale_price = product.saleprice,
                        cost_price = product.costprice,
                        quantity = product.productNum,
                        point = 0,
                        shopid = product.shopid
                    };
                    list3.Add(item);
                }
                orders.order_goods = list3;
                int num5 = new MxWeiXinPF.BLL.orders().Add(orders);
                if (num5 < 1)
                {
                    base.JscriptMsg("添加订单！", "back", "Error");
                }
                else
                {
                    this.id = num5;
                    this.ShowInfo(this.id);
                  //  base.JscriptMsg("添加商品成功！", "sale_order.aspx?id="+ num5, "Success");
                }
            }
        }

        private void ShowInfo(int _id)
        {
            this.model = new MxWeiXinPF.BLL.orders().GetModel(_id);
            this.Repeater1.DataSource = this.model.order_goods;
            this.Repeater1.DataBind();
            this.ddlexpress.SelectedValue = this.model.express_id.ToString();
            this.ddlpayment.SelectedValue = this.model.payment_id.ToString();
            this.id = _id;
            if (this.model.user_id > 0)
            {
                MxWeiXinPF.Model.users model = new MxWeiXinPF.BLL.users().GetModel(this.model.user_id);
                if (model != null)
                {
                    this.tbUserName.Text = model.user_name;
                    this.hopenid.Value = model.wxOpenId;
                    this.huserid.Value = model.id.ToString();
                    this.horderid.Value = _id.ToString();
                }
            }
        }

        private void TreeBind()
        {
            DataTable wCodeList = new MxWeiXinPF.BLL.wx_shop_category().GetWCodeList(this.wid, 0);
            this.ddlCategoryId.Items.Clear();
            this.ddlCategoryId.Items.Add(new ListItem("所有类别", ""));
            foreach (DataRow row in wCodeList.Rows)
            {
                string str = row["id"].ToString();
                int num = int.Parse(row["class_layer"].ToString());
                string text = row["title"].ToString().Trim();
                if (num == 1)
                {
                    this.ddlCategoryId.Items.Add(new ListItem(text, str));
                }
                else
                {
                    text = "├ " + text;
                    text = Utils.StringOfChar(num - 1, "　") + text;
                    this.ddlCategoryId.Items.Add(new ListItem(text, str));
                }
            }
        }
    }
}